package com.hgxd.service.impl;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.OSSObject;

import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hgxd.entity.pojo.DrawingManage;
import com.hgxd.mapper.DrawingManageMapper;
import com.hgxd.result.Result;

import com.hgxd.service.IDrawingManageService;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 * 图纸管理 服务实现类
 * </p>
 *
 * @author fsd
 * @since 2023-10-18
 */
@Service("DrawingManageServiceImpl")
public class DrawingManageServiceImpl extends ServiceImpl<DrawingManageMapper, DrawingManage> implements IDrawingManageService {
    @Resource
    DrawingManageMapper drawingManageMapper;

    public static void shangchuan() throws IOException {

        String endpoint = "http://oss-cn-beijing.aliyuncs.com";
        // 阿里云主账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维，请登录 https://ram.console.aliyun.com 创建RAM账号。
        String accessKeyId = "L*********SD";
        String accessKeySecret = "ExCm***************wcHF";
        String bucketName = "*******";
        String objectName = "456.txt";
        //objectName  上传文件名

        // 创建OSSClient实例。
        OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);

        // 上传内容到指定的存储空间（bucketName）并保存为指定的文件名称（objectName）。
        String content = "Hello OSS";
        //content 上传文件内容
        ossClient.putObject(bucketName, objectName, new ByteArrayInputStream(content.getBytes()));

        // 关闭OSSClient。
        ossClient.shutdown();
    }


    public static void fujianxiazai(HttpServletRequest request, HttpServletResponse response, String urlString) throws IOException {

        String endpoint = "*****************";
        // 阿里云主账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维，请登录 https://ram.console.aliyun.com 创建RAM账号。
        String accessKeyId = "*************";
        String accessKeySecret = "******************";
        String bucketName = "************";
        String objectName = urlString;

        response.reset();
        response.setContentType("application/x-msdownload");
        response.setHeader("Content-Disposition", "attachment;filename=" + new String(objectName.getBytes("utf-8"), "ISO8859-1"));
        // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>oss下载<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
        OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);

        String key = objectName.toString();
        key = key.replaceAll("\\\\", "/");
        OSSObject object = ossClient.getObject(bucketName, key);
        BufferedInputStream input = new BufferedInputStream(object.getObjectContent());
        byte[] buffBytes = new byte[1024];

        OutputStream outputStream = response.getOutputStream();

        int read = 0;
        while ((read = input.read(buffBytes)) != -1) {
            outputStream.write(buffBytes, 0, read);
        }

        outputStream.flush();
        outputStream.close();
        //is.close();
        input.close();
        ossClient.shutdown();

    }

    /**
     * 上传图片的实现类
     *
     * @param file
     * @return
     * @throws IOException
     */
    @Override
    public Result<String> upload(MultipartFile file) throws IOException {
        OSSClient ossClient = null;
        String objectName = null;
        try {
            String endpoint = "http://oss-cn-beijing.aliyuncs.com";
            // 阿里云主账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维，请登录 https://ram.console.aliyun.com 创建RAM账号。
            String accessKeyId = "LTAI5tGTEq7xnkNh4mruvrz8";
            String accessKeySecret = "JA3aPgqzznXCUVS0VicMVAe08FlQjp";
            // 创建OSSClient实例。
            ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
            // 上传内容到指定的存储空间（bucketName）并保存为指定的文件名称（objectName）。
            //content 上传文件内容
            String bucketName = "hgxd-02";
            objectName = UUID.randomUUID().toString().replaceAll("-", "").concat(".jpg");
            InputStream inputStream = file.getInputStream();
            System.out.println("file" + file);
//        ossClient.putObject(bucketName, objectName, inputStream);
            // 创建PutObjectRequest对象。
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, inputStream);
            // 创建PutObject请求。
            PutObjectResult result = ossClient.putObject(putObjectRequest);
            ossClient.shutdown();
            return Result.ok("https://hgxd-02.oss-cn-beijing.aliyuncs.com" + "/" + objectName);
        } catch (Exception oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }

        return Result.ok("https://hgxd-02.oss-cn-beijing.aliyuncs.com" + "/" + objectName);
    }


    /**
     * 下载图片的实现类
     *
     * @param request
     * @param response
     * @param urlString
     * @return
     * @throws IOException
     */

    @Override
    public Result<String> download(HttpServletRequest request, HttpServletResponse response, String urlString) throws IOException {
        String endpoint = "http://oss-cn-beijing.aliyuncs.com";
        // 阿里云主账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维，请登录 https://ram.console.aliyun.com 创建RAM账号。
        String accessKeyId = "LTAI5tGTEq7xnkNh4mruvrz8";
        String accessKeySecret = "JA3aPgqzznXCUVS0VicMVAe08FlQjp";
        String bucketName = "hgxd-02";
        String objectName = urlString;
        response.reset();
        response.setContentType("application/x-msdownload");
        response.setHeader("Content-Disposition", "attachment;filename=" + new String(objectName.getBytes("utf-8"), "ISO8859-1"));
        // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>oss下载<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
        OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);

        String key = objectName.toString();
        key = key.replaceAll("\\\\", "/");
        OSSObject object = ossClient.getObject(bucketName, key);
        BufferedInputStream input = new BufferedInputStream(object.getObjectContent());
        byte[] buffBytes = new byte[1024];

        OutputStream outputStream = response.getOutputStream();

        int read = 0;
        while ((read = input.read(buffBytes)) != -1) {
            outputStream.write(buffBytes, 0, read);
        }

        outputStream.flush();
        outputStream.close();
        //is.close();
        input.close();
        ossClient.shutdown();
        return null;
    }

    @Override
    public List<DrawingManage> getDrawingByType(String type) {
        return drawingManageMapper.getDrawingByType(type);
    }


}
